package com.jinwei.qunguanjia.system.service;

import com.jinwei.qunguanjia.system.dto.SysLoginUser;
import com.jinwei.qunguanjia.common.constant.CacheConstants;
import com.jinwei.qunguanjia.common.constant.Constants;
import com.jinwei.qunguanjia.common.core.redis.RedisCache;
import com.jinwei.qunguanjia.common.utils.*;
import com.jinwei.qunguanjia.common.utils.ip.AddressUtils;
import com.jinwei.qunguanjia.common.utils.ip.IpUtils;
import eu.bitwalker.useragentutils.UserAgent;

import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * token验证处理
 *
 * @author ruoyi
 */
@Component
public class TokenService {

    @Resource
    private RedisCache redisCache;

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public SysLoginUser getLoginUser(HttpServletRequest request)
    {
        // 获取请求携带的令牌
        String token = getToken(request);
        if (StringUtils.isNotEmpty(token))
        {
            String userKey = getBackendTokenKey(token);
            return redisCache.getCacheObject(userKey);
        }
        return null;
    }

    /**
     * 设置用户身份信息
     */
    public void setLoginUser(SysLoginUser loginUser)
    {
        if (StringUtils.isNotNull(loginUser) && StringUtils.isNotEmpty(loginUser.getToken()))
        {
            refreshToken(loginUser);
        }
    }

    /**
     * 删除用户身份信息
     */
    public void delLoginUser(String token, String userName)
    {
        if (StringUtils.isNotEmpty(token))
        {
            String userKey = getBackendTokenKey(token);
            String userNameKey = getBackendUserNameKey(userName);
            redisCache.deleteObject(userKey);
            redisCache.deleteObject(userNameKey);
        }
    }

    /**
     * 创建令牌
     *
     * @param loginUser 用户信息
     * @return 令牌
     */
    String createToken(SysLoginUser loginUser)
    {
        String token = UUIDUtils.getUUID();
        loginUser.setToken(token);
        setUserAgent(loginUser);
        refreshToken(loginUser);
        return token;
    }

    /**
     * 刷新令牌有效期
     *
     * @param loginUser 登录信息
     */
    private void refreshToken(SysLoginUser loginUser)
    {
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(DateUtils.getOffsetDay(5));
        // 根据uuid将loginUser缓存
        String userKey = getBackendTokenKey(loginUser.getToken());
        String userNameKey = getBackendUserNameKey(loginUser.getUsername());
        redisCache.setCacheObject(userNameKey, loginUser.getToken(), DateUtils.getOffsetDay(5), TimeUnit.MILLISECONDS);
        redisCache.setCacheObject(userKey, loginUser, DateUtils.getOffsetDay(5), TimeUnit.MILLISECONDS);
    }

    /**
     * 设置用户代理信息
     *
     * @param loginUser 登录信息
     */
    private void setUserAgent(SysLoginUser loginUser)
    {
        UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
        loginUser.setIpAddress(ip);
        loginUser.setLoginLocation(AddressUtils.getRealAddressByIP(ip));
        loginUser.setBrowser(userAgent.getBrowser().getName());
        loginUser.setOs(userAgent.getOperatingSystem().getName());
    }

    /**
     * 获取请求token
     *
     * @return token
     */
    private String getToken(HttpServletRequest request)
    {
        String token = request.getHeader(Constants.TOKEN_HEADER);
        if (StringUtils.isNotEmpty(token) && token.startsWith(Constants.TOKEN_PREFIX))
        {
            token = token.replace(Constants.TOKEN_PREFIX, "");
        }
        return token;
    }

    /**
     * 获取请求租户id
     *
     * @return 租户id
     */
    public String getTenantId(HttpServletRequest request) {
        return request.getHeader(Constants.TENANT_ID_HEADER);
    }

    public String getBackendTokenKey(String uuid) {
        return String.format(CacheConstants.BACKEND_LOGIN_TOKEN_KEY) + uuid;
    }

    public String getBackendUserNameKey(String userName) {
        return String.format(CacheConstants.BACKEND_LOGIN_USER_NAME_KEY) + userName;
    }
}
